package service

import (
	"github.com/thinkeridea/go-extend/exunicode/exutf8"
	"mogu-go-v2/common"
	"mogu-go-v2/models"
	"mogu-go-v2/models/maps"
	"reflect"
	"strconv"
	"strings"
	"sync"
	"unicode/utf8"
	"encoding/json"
	"io/ioutil"
	"github.com/rs/xid"
	"net/http"
	urlLib "net/url"
	"fmt"
	"regexp"
	"path"
	"os"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

/**
 *
 * @author  镜湖老杨
 * @date  2021/1/28 1:11 下午
 * @version 1.0
 */

type blogService struct {
	wg sync.WaitGroup
}

func (blogService) DeleteRedisByBlog() {
	common.RedisUtil.Delete("NEW_BLOG")
	common.RedisUtil.Delete("HOT_BLOG")
	common.RedisUtil.Delete("BLOG_LEVEL:1")
	common.RedisUtil.Delete("BLOG_LEVEL:2")
	common.RedisUtil.Delete("BLOG_LEVEL:3")
	common.RedisUtil.Delete("BLOG_LEVEL:4")
}

func (blogService) AddVerdict(count int64, level int) string {
	switch level {
	case 1:
		blogCount, _ := SysParamService.GetSysParamsValueByKey("BLOG_FIRST_COUNT")
		i, _ := strconv.Atoi(blogCount)
		if count > int64(i) {
			return "一级推荐不能超过" + blogCount + "个"
		}
		break
	case 2:
		blogCount, _ := SysParamService.GetSysParamsValueByKey("BLOG_SECOND_COUNT")
		i, _ := strconv.Atoi(blogCount)
		if count > int64(i) {
			return "二级推荐不能超过" + blogCount + "个"
		}
		break
	case 3:
		blogCount, _ := SysParamService.GetSysParamsValueByKey("BLOG_THIRD_COUNT")
		i, _ := strconv.Atoi(blogCount)
		if count > int64(i) {
			return "三级推荐不能超过" + blogCount + "个"
		}
		break
	case 4:
		blogCount, _ := SysParamService.GetSysParamsValueByKey("BLOG_FOURTH_COUNT")
		i, _ := strconv.Atoi(blogCount)
		if count > int64(i) {
			return "四级推荐不能超过" + blogCount + "个"
		}
		break
	default:
		return ""
	}
	return ""
}

func (blogService) UpdateSolrAndRedis(isSave bool, blog models.Blog) {
	if isSave && blog.IsPublish == "1" {
		/*m:=map[string]interface{}{
			"command":"add",
			"blog_uid":blog.Uid,
		}*/
	}
}

func (c *blogService) DeleteRedisByBlogSort() {
	common.RedisUtil.Delete("DASHBOARD:BLOG_COUNT_BY_SORT")
	c.DeleteRedisByBlog()
}

func (c *blogService) DeleteRedisByBlogTag() {
	common.RedisUtil.Delete("DASHBOARD:BLOG_COUNT_BY_TAG")
	c.DeleteRedisByBlog()
}

func (s *blogService) SetTagAndSortAndPictureByBlogList(list []models.Blog) []models.Blog {
	var sortUids, tagUids, fileUidsSet []string
	for _, item := range list {
		if item.FileUid != "" {
			fileUidsSet = append(fileUidsSet, item.FileUid)
		}
		if item.BlogSortUid != "" {
			sortUids = append(sortUids, item.BlogSortUid)
		}
		if item.TagUid != "" {
			tagUidsTemp := strings.Split(item.TagUid, ",")
			for _, itemTagUid := range tagUidsTemp {
				tagUids = append(tagUids, itemTagUid)
			}
		}
	}
	var pictureList map[string]interface{}
	var str []string
	var picList []map[string]interface{}
	fileUidsSet = common.RemoveRepByMap(fileUidsSet)
	if len(fileUidsSet) > 0 {
		count := 1
		var fileUids string
		for _, fileUid := range fileUidsSet {
			str = append(str, fileUid+",")
			l.Print(count % 10)
			if count%10 == 0 {
				fileUids = strings.Join(str, ",")
				pictureList = FileService.GetPicture(fileUids, ",")
				tempPicList := common.WebUtil.GetPictureMap(pictureList)
				picList = append(picList, tempPicList...)
				str = []string{}
			}
			count++
		}
		if len(str) >= 32 {
			pictureList = FileService.GetPicture(fileUids, ",")
			tempPicList := common.WebUtil.GetPictureMap(pictureList)
			picList = append(picList, tempPicList...)
		}
	}
	var sortList []models.BlogSort
	var tagList []models.Tag
	s.wg.Add(1)
	go func() {
		if len(str) > 0 {
			common.DB.Find(&sortList, sortUids)
		}
		s.wg.Done()
	}()
	s.wg.Add(1)
	go func() {
		if len(tagUids) > 0 {
			common.DB.Find(&tagList, tagUids)
		}
		s.wg.Done()
	}()
	s.wg.Wait()
	sortMap := map[string]models.BlogSort{}
	tagMap := map[string]models.Tag{}
	pictureMap := map[string]string{}
	s.wg.Add(1)
	go func() {
		for _, item := range sortList {
			sortMap[item.Uid] = item
		}
		s.wg.Done()
	}()
	s.wg.Add(1)
	go func() {
		for _, item := range tagList {
			tagMap[item.Uid] = item
		}
		s.wg.Done()
	}()
	s.wg.Add(1)
	go func() {
		for _, item := range picList {
			pictureMap[item["uid"].(string)] = item["url"].(string)
		}
		s.wg.Done()
	}()
	s.wg.Wait()
	for i, item := range list {
		s.wg.Add(3)
		item := item
		i := i
		go func() {
			if item.BlogSortUid != "" {
				list[i].BlogSort = sortMap[item.BlogSortUid]
				if sortMap[item.BlogSortUid] != (models.BlogSort{}) {
					list[i].BlogSortName = sortMap[item.BlogSortUid].SortName
				}
			}
			s.wg.Done()
		}()
		go func() {
			if item.TagUid != "" {
				tagUidsTemp := strings.Split(item.TagUid, ",")
				var tagListTemp []models.Tag
				for _, tag := range tagUidsTemp {
					tagListTemp = append(tagListTemp, tagMap[tag])
				}
				list[i].TagList = tagListTemp
			}
			s.wg.Done()
		}()
		go func() {
			if item.FileUid != "" {
				pictureUidsTemp := strings.Split(item.FileUid, ",")
				var pictureListTemp []string
				for _, picture := range pictureUidsTemp {
					pictureListTemp = append(pictureListTemp, picture)
				}
				list[i].PhotoList = pictureListTemp
				if len(pictureListTemp) > 0 {
					list[i].PhotoUrl = pictureListTemp[0]
				} else {
					list[i].PhotoUrl = ""
				}
			}
			s.wg.Done()
		}()
	}
	s.wg.Wait()
	return list
}

func (s *blogService) GetBlogPageByLevel(currentPage int, pageSize int, level int, userSort int) ([]models.BlogNoContent, int64) {
	var pageList []models.BlogNoContent
	var order string
	if userSort == 0 {
		order = "create_time desc"
	} else {
		order = "sort desc"
	}
	var total int64
	s.wg.Add(2)
	go func() {
		common.DB.Model(&models.Blog{}).Where("level=? and status=? and is_publish=?", level, 1, "1", 1).Count(&total)
		s.wg.Done()
	}()
	go func() {
		common.DB.Where("level=? and status=? and is_publish=?", level, 1, "1").Offset((currentPage - 1) * pageSize).Limit(pageSize).Order(order).Find(&pageList)
		s.wg.Done()
	}()
	s.wg.Wait()
	return pageList, total
}

func (s *blogService) SetBlog(list []models.BlogNoContent) []models.BlogNoContent {
	var fileUids strings.Builder
	var sortUids []string
	var tagUids []string
	for _, item := range list {
		if item.FileUid != "" {
			fileUids.WriteString(item.FileUid + ",")
		}
		if item.BlogSortUid != "" {
			sortUids = append(sortUids, item.BlogSortUid)
		}
		if item.TagUid != "" {
			tagUids = append(tagUids, item.TagUid)
		}
	}
	pictureList := map[string]interface{}{}
	if !reflect.DeepEqual(fileUids, strings.Builder{}) {
		pictureList = FileService.GetPicture(fileUids.String(), ",")
	}
	picList := common.WebUtil.GetPictureMap(pictureList)
	var sortList []models.BlogSort
	var tagList []models.Tag
	s.wg.Add(1)
	go func() {
		if len(sortUids) > 0 {
			common.DB.Find(&sortList, sortUids)
		}
		s.wg.Done()
	}()
	s.wg.Add(1)
	go func() {
		if len(tagUids) > 0 {
			common.DB.Find(&tagList, tagUids)
		}
		s.wg.Done()
	}()
	s.wg.Wait()
	sortMap := map[string]models.BlogSort{}
	tagMap := map[string]models.Tag{}
	pictureMap := map[string]string{}
	for _, item := range sortList {
		sortMap[item.Uid] = item
	}
	for _, item := range tagList {
		tagMap[item.Uid] = item
	}
	for _, item := range picList {
		pictureMap[item["uid"].(string)] = item["url"].(string)
	}
	for i, item := range list {
		if item.BlogSortUid != "" {
			list[i].BlogSort = sortMap[item.BlogSortUid]
		}
		if item.TagUid != "" {
			tagUidsTemp := strings.Split(item.TagUid, ",")
			var tagListTemp []models.Tag
			for _, tag := range tagUidsTemp {
				if tagMap[tag] != (models.Tag{}) {
					tagListTemp = append(tagListTemp, tagMap[tag])
				}
			}
			list[i].TagList = tagListTemp
		}
		if item.FileUid != "" {
			pictureUidsTemp := strings.Split(item.FileUid, ",")
			var pictureListTemp []string
			for _, picture := range pictureUidsTemp {
				pictureListTemp = append(pictureListTemp, pictureMap[picture])
			}
			list[i].PhotoList = pictureListTemp
		}
	}
	return list
}

func (s *blogService) SetTagAndSortAndPictureByBlogListNoContent(list []models.BlogNoContent) []models.BlogNoContent {
	var sortUids, tagUids, fileUidsSet []string
	for _, item := range list {
		if item.FileUid != "" {
			fileUidsSet = append(fileUidsSet, item.FileUid)
		}
		if item.BlogSortUid != "" {
			sortUids = append(sortUids, item.BlogSortUid)
		}
		if item.TagUid != "" {
			tagUidsTemp := strings.Split(item.TagUid, ",")
			for _, itemTagUid := range tagUidsTemp {
				tagUids = append(tagUids, itemTagUid)
			}
		}
	}
	var pictureList map[string]interface{}
	var str []string
	var picList []map[string]interface{}
	fileUidsSet = common.RemoveRepByMap(fileUidsSet)
	if len(fileUidsSet) > 0 {
		count := 1
		var fileUids string
		for _, fileUid := range fileUidsSet {
			str = append(str, fileUid+",")
			l.Print(count % 10)
			if count%10 == 0 {
				fileUids = strings.Join(str, ",")
				pictureList = FileService.GetPicture(fileUids, ",")
				tempPicList := common.WebUtil.GetPictureMap(pictureList)
				picList = append(picList, tempPicList...)
				str = []string{}
			}
			count++
		}
		if len(str) >= 32 {
			pictureList = FileService.GetPicture(fileUids, ",")
			tempPicList := common.WebUtil.GetPictureMap(pictureList)
			picList = append(picList, tempPicList...)
		}
	}
	var sortList []models.BlogSort
	var tagList []models.Tag
	s.wg.Add(2)
	go func() {
		if len(str) > 0 {
			common.DB.Find(&sortList, sortUids)
		}
		s.wg.Done()
	}()
	go func() {
		if len(tagUids) > 0 {
			common.DB.Find(&tagList, tagUids)
		}
		s.wg.Done()
	}()
	s.wg.Wait()
	sortMap := map[string]models.BlogSort{}
	tagMap := map[string]models.Tag{}
	pictureMap := map[string]string{}
	for _, item := range sortList {
		sortMap[item.Uid] = item
	}
	for _, item := range tagList {
		tagMap[item.Uid] = item
	}
	for _, item := range picList {
		pictureMap[item["uid"].(string)] = item["url"].(string)
	}
	for i, item := range list {
		item := item
		i := i
		go func() {
			if item.BlogSortUid != "" {
				list[i].BlogSort = sortMap[item.BlogSortUid]
				if sortMap[item.BlogSortUid] != (models.BlogSort{}) {
					list[i].BlogSortName = sortMap[item.BlogSortUid].SortName
				}
			}
		}()
		go func() {
			if item.TagUid != "" {
				tagUidsTemp := strings.Split(item.TagUid, ",")
				var tagListTemp []models.Tag
				for _, tag := range tagUidsTemp {
					tagListTemp = append(tagListTemp, tagMap[tag])
				}
				list[i].TagList = tagListTemp
			}
		}()
		go func() {
			if item.FileUid != "" {
				pictureUidsTemp := strings.Split(item.FileUid, ",")
				var pictureListTemp []string
				for _, picture := range pictureUidsTemp {
					pictureListTemp = append(pictureListTemp, picture)
				}
				list[i].PhotoList = pictureListTemp
				if len(pictureListTemp) > 0 {
					list[i].PhotoUrl = pictureListTemp[0]
				} else {
					list[i].PhotoUrl = ""
				}
			}
		}()
	}
	return list
}

func (*blogService) GetHitCode(str, keyword string) string {
	if str == "" || keyword == "" {
		return str
	}
	startStr := "<span style = 'color:red'>"
	endStr := "</span>"
	if str == keyword {
		return startStr + str + endStr
	}
	lowerCaseStr := strings.ToLower(str)
	lowerKeyword := strings.ToLower(keyword)
	lowerCaseArray := strings.Split(lowerCaseStr, lowerKeyword)
	isEndWith := strings.HasSuffix(lowerCaseStr, lowerKeyword)
	var count int
	var list []map[string]int
	var keyList []map[string]int
	for a := 0; a < len(lowerCaseArray); a++ {
		m := map[string]int{}
		keyMap := make(map[string]int)
		m["startIndex"] = count
		l := utf8.RuneCountInString(lowerCaseArray[a])
		count += l
		m["endIndex"] = count
		list = append(list, m)
		if a < len(lowerCaseArray)-1 || isEndWith {
			keyMap["startIndex"] = count
			count += utf8.RuneCountInString(keyword)
			keyMap["endIndex"] = count
			keyList = append(keyList, keyMap)
		}
	}
	var arrayList []string
	for _, item := range list {
		start := item["startIndex"]
		end := item["endIndex"]
		itemStr := exutf8.RuneSubString(str, start, end-start)
		arrayList = append(arrayList, itemStr)
	}
	var keyArrayList []string
	for _, item := range keyList {
		start := item["startIndex"]
		end := item["endIndex"]
		itemStr := exutf8.RuneSubString(str, start, end-start)
		keyArrayList = append(keyArrayList, itemStr)
	}
	var sb strings.Builder
	for a := 0; a < len(arrayList); a++ {
		sb.WriteString(arrayList[a])
		if a < len(arrayList)-1 || isEndWith {
			sb.WriteString(startStr)
			sb.WriteString(keyArrayList[a])
			sb.WriteString(endStr)
		}
	}
	return sb.String()
}

func (*blogService) SetTagByBlog(blog *models.Blog) {
	tagUid := blog.TagUid
	if tagUid != "" {
		uids := strings.Split(tagUid, ",")
		var tagList []models.Tag
		for _, uid := range uids {
			var tag models.Tag
			common.DB.Where("uid=?", uid).Find(&tag)
			if tag != (models.Tag{}) && tag.Status != 0 {
				tagList = append(tagList, tag)
			}
		}
		blog.TagList = tagList
	}
}

func (*blogService) SetSortByBlog(blog *models.Blog) {
	if !reflect.DeepEqual(blog, models.Blog{}) && blog.BlogSortUid != "" {
		var blogSort models.BlogSort
		common.DB.Where("uid=?", blog.BlogSortUid).Find(&blogSort)
		blog.BlogSort = blogSort
	}
}

func (s *blogService) SetTagAndSortByBlogList(list []models.Blog) []models.Blog {
	var sortUids []string
	var tagUids []string
	for _, item := range list {
		if item.BlogSortUid != "" {
			sortUids = append(sortUids, item.BlogSortUid)
		}
		if item.TagUid != "" {
			tagUidsTemp := strings.Split(item.TagUid, ",")
			for _, itemTagUid := range tagUidsTemp {
				tagUids = append(tagUids, itemTagUid)
			}
		}
	}
	var sortList []models.BlogSort
	var tagList []models.Tag
	s.wg.Add(2)
	go func() {
		if len(sortUids) > 0 {
			common.DB.Find(&sortList, sortUids)
		}
		s.wg.Done()
	}()
	go func() {
		if len(tagUids) > 0 {
			common.DB.Find(&tagList, tagUids)
		}
		s.wg.Done()
	}()
	s.wg.Wait()
	sortMap := map[string]models.BlogSort{}
	tagMap := map[string]models.Tag{}
	for _, item := range sortList {
		sortMap[item.Uid] = item
	}
	for _, item := range tagList {
		tagMap[item.Uid] = item
	}
	for i, item := range list {
		if item.BlogSortUid != "" {
			list[i].BlogSort = sortMap[item.BlogSortUid]
		}
		if item.TagUid != "" {
			tagUidsTemp := strings.Split(item.TagUid, ",")
			var tagListTemp []models.Tag
			for _, tag := range tagUidsTemp {
				tagListTemp = append(tagListTemp, tagMap[tag])
			}
			list[i].TagList = tagListTemp
		}
	}
	return list
}


func (s *blogService) SavePost(url string, dir string,httpHost string, blogSortUid string) string{
	resp, err := http.Get(url)
	rootdir, _ := os.Getwd()
	fileDir := rootdir + dir
	if err != nil {
		return "出现错误"
		fmt.Println(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(body))
	//fmt.Println(url)
	if err != nil {
		return "出现错误"
	}

	var jsonWpObj maps.WpMap
	json.Unmarshal([]byte(body), &jsonWpObj)

	//判断是否存在
	//2、批量更新
	var blog models.Blog
	common.DB.Where("oid=?", jsonWpObj.Id).Find(&blog)
	fmt.Println(jsonWpObj.Id)

	//<img src="([^"]*)"
	//<a href="([^"]*)"[\s][^>]*>([^<]*)
	const con string = `<img src="([^"]*)"`
	r := regexp.MustCompile(con)
	//m := r.FindStringSubmatch(jsonWpObj.Content.Rendered)
	m := r.FindAllStringSubmatch(jsonWpObj.Content.Rendered, -1)
	//fmt.Println(reflect.TypeOf(m))
	newContent := jsonWpObj.Content.Rendered
	if len(m) > 0 {
		//tmpContent := jsonWpObj.Content.Rendered
		for _,mm := range m{
			if strings.Contains(mm[1],"shanhubei") {
				newFileDir := fileDir + "/" + path.Base(mm[1])
				newHttpFile := httpHost + dir + "/" + path.Base(mm[1])
				//s.wg.Add(1)
				//go func(){
					common.FileUtil.SaveFile(mm[1],newFileDir, fileDir)
					//s.wg.Done()
				//}()
				//tmpContent := r.ReplaceAllLiteralString(jsonWpObj.Content.Rendered, newCon)
				//fmt.Println(jsonWpObj.Content.Rendered)
				newContent = strings.Replace(newContent, mm[1], newHttpFile, -1)
			}
			
		}
		//s.wg.Wait()
		//fmt.Println(newContent)
	}
	newContent = newContent+"<br>来源：<p>"+jsonWpObj.Link + "</p>"
	//for _,mm := range m{
		//这里使用string(mm[2]),是为了后面打印出来直接可以用%s
		//result.Items = append(result.Items,string(mm[2]))
		//result.Requests = append(result.Requests,engine.Request{mm[1],engine.NilParseFunc})
		//fmt.Println(mm)
	//}
	if reflect.DeepEqual(blog, models.Blog{}) {
		blog.Author = "robot"
		blog.AdminUid = "1f01cd1d2f474743b241d74008b12333"
		blog.ArticlesPart = "珊瑚贝"
		blog.Uid = xid.New().String()
		blog.Title = jsonWpObj.Title.Rendered
		blog.Summary = jsonWpObj.Excerpt.Rendered
		blog.Content = newContent
		blog.TagUid = "ccgpd8b9eba9ac9hsvmg"
		blog.BlogSortUid = blogSortUid
		blog.FileUid = "cavagbb9eba9ag02lea0"
		blog.Level = 1
		blog.IsOriginal = "1"
		blog.IsPublish = "1"
		blog.OpenComment = "1"
		blog.Type = "0"
		blog.OutsideLink = ""
		blog.Oid = jsonWpObj.Id
		common.DB.Create(&blog)
		common.RedisUtil.Delete("BLOG_LEVEL:" + strconv.Itoa(blog.Level))
		//fmt.Println("新增成功")
		return "新增成功"
	}else{
		//更新
		blog.Author = "robot"
		blog.AdminUid = "1f01cd1d2f474743b241d74008b12333"
		blog.ArticlesPart = "珊瑚贝"
		blog.Title = jsonWpObj.Title.Rendered
		blog.Summary = jsonWpObj.Excerpt.Rendered
		blog.Content = newContent
		blog.TagUid = "ccgpd8b9eba9ac9hsvmg"
		blog.BlogSortUid = blogSortUid
		blog.FileUid = "cavagbb9eba9ag02lea0"
		blog.Level = 1
		blog.IsOriginal = "1"
		blog.IsPublish = "1"
		blog.OpenComment = "1"
		blog.Type = "0"
		blog.OutsideLink = ""
		blog.Oid = jsonWpObj.Id
		common.DB.Save(&blog)
		common.RedisUtil.Delete("BLOG_LEVEL:" + strconv.Itoa(blog.Level))
		//fmt.Println("更新成功")
		return "更新成功"
	}
}


func (s *blogService) SavePostWpArr(httpHost string, requestUrl string, sortId string, sleepTime int) string{

		//c.SuccessWithMessage("todo")
		//url := c.GetString("url")
		url := requestUrl
		u, _ := urlLib.Parse(requestUrl)
		fileDir := "/shbimages/"+ strings.Replace(u.Host, ".", "_", -1)

		//1、单独更新；2、批量更新
		resp, err := http.Get(url)
		if err != nil {
			fmt.Println(err)
		}
		defer resp.Body.Close()
		header := resp.Header
		totalPage,_ := strconv.Atoi(header["X-Wp-Totalpages"][0])
		//totalPage := 10
		baseUrl := u.Scheme + "://"+ u.Host +"/wp-json/wp/v2/posts/"
		//baseUrl := url
		//requestUrl := baseUrl + 
		body, err := ioutil.ReadAll(resp.Body)
		//fmt.Println(string(body))
		if err != nil {
			fmt.Println(err)
		}
		var jsonWpObjs []maps.WpMap
		json.Unmarshal([]byte(body), &jsonWpObjs)
	
		//page=1 直接用以前的
		for _, jsonWpObj := range jsonWpObjs {
			//fmt.Println(jsonWpObj.Id)
			result := s.SavePostWp(baseUrl + strconv.Itoa(jsonWpObj.Id), fileDir,httpHost,sortId)
			time.Sleep(time.Duration(sleepTime)*time.Second)
			fmt.Println(result)
		}
	
		if totalPage > 1 {
			fmt.Println("totalPage=",totalPage)
			//page=2
			page := 2
			for page =2; page <= totalPage; page ++{
				fmt.Println("正在采集页面 page=",page)
				var pageUrl string
				if strings.Contains(url,"?") {
					pageUrl = url+"&page=" + strconv.Itoa(page)
				}else{
					pageUrl = url+"?page=" + strconv.Itoa(page)
				}
				//fmt.Println("pageUrl=",pageUrl)
				postlistView, err := http.Get(pageUrl)
				if err != nil {
					fmt.Println(err)
				}
				defer postlistView.Body.Close()
				bodyview, _ := ioutil.ReadAll(postlistView.Body)
				jsonWpObjs = []maps.WpMap{}
				json.Unmarshal([]byte(bodyview), &jsonWpObjs)
				for _, jsonWpObj := range jsonWpObjs {
					//c.Wg.Add(1)
					postUrl := baseUrl + strconv.Itoa(jsonWpObj.Id)
					//go func(){
						fmt.Println("postUrl=",postUrl)
						//result := service.BlogService.SavePost(postUrl,fileDir,httpHost)
						fmt.Println(s.SavePostWp(postUrl,fileDir,httpHost,sortId))
						time.Sleep(time.Duration(sleepTime)*time.Second)
						//c.Wg.Done()
					//}()
				}
				//c.Wg.Wait()
			}
		}

	return "SavePostWpArr成功"
}

func (s *blogService) SavePostWp(url string, dir string,httpHost string, blogSortUid string) string{
	resp, err := http.Get(url)
	rootdir, _ := os.Getwd()
	fileDir := rootdir + dir
	if err != nil {
		return "出现错误"
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	//fmt.Println(string(body))
	//fmt.Println(url)
	if err != nil {
		return "出现错误"
	}

	var jsonWpObj maps.WpMap
	json.Unmarshal([]byte(body), &jsonWpObj)

	//判断是否存在
	//2、批量更新
	var blog models.Blog
	common.DB.Where("oid=?", jsonWpObj.Id).Find(&blog)
	fmt.Println(jsonWpObj.Id)

	//<img src="([^"]*)"
	//<a href="([^"]*)"[\s][^>]*>([^<]*)
	//const con string = `<img class="([^"]*)" src="([^"]*)"`
	con,_ := beego.AppConfig.String("crawel_img_url")
	imgIndex,_ :=  beego.AppConfig.Int64("crawel_img_index")
	r := regexp.MustCompile(con)
	//m := r.FindStringSubmatch(jsonWpObj.Content.Rendered)
	m := r.FindAllStringSubmatch(jsonWpObj.Content.Rendered, -1)
	//fmt.Println(reflect.TypeOf(m))
	newContent := jsonWpObj.Content.Rendered
	if len(m) > 0 {
		//tmpContent := jsonWpObj.Content.Rendered
		for _,mm := range m{
			newFileDir := fileDir + "/" + path.Base(mm[imgIndex])
			newHttpFile := httpHost + dir + "/" + path.Base(mm[imgIndex])
			//s.wg.Add(1)
			//go func(){
				common.FileUtil.SaveFile(mm[imgIndex],newFileDir, fileDir)
				//s.wg.Done()
			//}()
			//tmpContent := r.ReplaceAllLiteralString(jsonWpObj.Content.Rendered, newCon)
			//fmt.Println(jsonWpObj.Content.Rendered)
			newContent = strings.Replace(newContent, mm[imgIndex], newHttpFile, -1)			
		}
		//s.wg.Wait()
		//fmt.Println(newContent)
	}
	//newContent = newContent+"<br>来源：<p>"+jsonWpObj.Link + "</p>"
	//for _,mm := range m{
		//这里使用string(mm[2]),是为了后面打印出来直接可以用%s
		//result.Items = append(result.Items,string(mm[2]))
		//result.Requests = append(result.Requests,engine.Request{mm[1],engine.NilParseFunc})
		//fmt.Println(mm)
	//}
	//post 请求
	postData := urlLib.Values{}
	postData.Add("post_title", jsonWpObj.Title.Rendered)
	postData.Add("post_category", blogSortUid)
	postData.Add("post_content", newContent)
	respPost, err := http.Post("http://www.shanhubei.com/postarticle/hm-locowp.php?action=save&secret=abcd1234s",
        "application/x-www-form-urlencoded",
        strings.NewReader(postData.Encode()))
    if err != nil {
        fmt.Println(err)
    }
 
    defer respPost.Body.Close()
    bodyPost, err := ioutil.ReadAll(respPost.Body)
    if err != nil {
        // handle error
    }
    fmt.Println(string(bodyPost))

	return "更新成功"
}

var BlogService = &blogService{}
